package com.pervasive.mqtt;

import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttNotConnectedException;
import com.ibm.mqtt.MqttPersistence;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;

public class MQTTConnection implements MqttSimpleCallback{
	
	private static final String		MQTT_HOST = "156.56.94.8";
	private static int				MQTT_BROKER_PORT_NUM      = 1883;
	private static MqttPersistence	MQTT_PERSISTENCE          = null;
	private static boolean			MQTT_CLEAN_START          = true;
	private static short			MQTT_KEEP_ALIVE           = 60 * 15;
	private static int[]			MQTT_QUALITIES_OF_SERVICE = { 0 } ;
	private static int				MQTT_QUALITY_OF_SERVICE   = 0;
	private static boolean			MQTT_RETAINED_PUBLISH     = false;
	
	private static final String id = "XMN1111poTr";
	
	private static final String data_open_line = "card_status";
	
	IMqttClient mqttClient = null;
	
	public MQTTConnection()
	{
		String mqttConnSpec = "tcp://" + MQTT_HOST + "@" + MQTT_BROKER_PORT_NUM;
		
		try {
			mqttClient = MqttClient.createMqttClient(mqttConnSpec, MQTT_PERSISTENCE);
			
			mqttClient.connect(id, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
			
			mqttClient.registerSimpleHandler(this);
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	@Override
	public void connectionLost() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void publishArrived(String arg0, byte[] arg1, int arg2, boolean arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	public void sendUpdate(String message) {		
		
			//System.out.println(" ==== Publishing Data --> "+message);
			try {
				mqttClient.publish(data_open_line, 
								   message.getBytes(),
								   MQTT_QUALITY_OF_SERVICE, 
								   MQTT_RETAINED_PUBLISH);
			} catch (MqttNotConnectedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MqttPersistenceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

}
